package com.example.controller;

import com.example.config.EncryptionConfig;
import com.example.dto.EncryptedRequestDTO;
import com.example.dto.Request;
import com.example.dto.Response;
import com.example.util.AesUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/crypto")
public class CryptoController {

    @Autowired
    private EncryptionConfig encryptionConfig;

    @Autowired
    private ObjectMapper objectMapper; // 用于 JSON 序列化和反序列化

    @PostMapping("/encrypt")
    public String encrypt(@RequestBody String requestBody) {
        String encryptedBody = AesUtil.encrypt(encryptionConfig.getKey(), encryptionConfig.getInitVector(), requestBody);
        return encryptedBody;
    }

    @PostMapping("/decrypt")
    public String decrypt(@RequestBody String requestBody) {
        String decryptedBody = AesUtil.decrypt(encryptionConfig.getKey(), encryptionConfig.getInitVector(), requestBody);
        return decryptedBody;
    }

    /**
     * 加密 Request 对象，并返回加密后的字符串
     *
     * @param request 要加密的请求体
     * @param <T>     请求数据的类型
     * @return 加密后的字符串
     * @throws JsonProcessingException JSON 处理异常
     */
    @PostMapping("/encrypt/json")
    public <T> String encryptJson(@RequestBody Request<T> request) throws JsonProcessingException {
        // 将 Request 对象序列化为 JSON 字符串
        String jsonString = objectMapper.writeValueAsString(request);
        // 加密 JSON 字符串
        String encryptedBody = AesUtil.encrypt(encryptionConfig.getKey(), encryptionConfig.getInitVector(), jsonString);
        return encryptedBody;
    }

    /**
     * 解密字符串，并返回解密后的 Response 对象
     *
     * @param encryptedRequest 包含加密数据的请求体 DTO
     * @param <T>              响应数据的类型
     * @return 解密后的响应对象
     * @throws JsonProcessingException JSON 处理异常
     */
    @PostMapping("/decrypt/json")
    public <T> Response<T> decryptJson(@RequestBody EncryptedRequestDTO encryptedRequest) throws JsonProcessingException {
        // 解密 JSON 字符串
        String decryptedBody = AesUtil.decrypt(encryptionConfig.getKey(), encryptionConfig.getInitVector(), encryptedRequest.getEncryptedData());
        // 将解密后的 JSON 字符串反序列化为 Response 对象
        Response response = objectMapper.readValue(decryptedBody, Response.class);
        return response;
    }
}
